import modelAbstract from "./modelAbstract"
import {image} from "../service/images"
import config from "../../config"
import bulletCan from "../canvas/bullet"
import {directionEnum} from "../enum/directionEnum"
import touchUtil from "../utils/touch";
import wall from "../canvas/wall"
import steels from "../canvas/steels";
import boss from "../canvas/boss"
import enemy from "../canvas/enemy";
import player from "../canvas/player";
import audio from "../service/audio";

export default class bullet extends modelAbstract implements IModel {
  name: string = 'bullet'
  public canvas: ICanvas = bulletCan

  image(): HTMLImageElement {
    return image.get('bullet')!
  }

  constructor(public tank: IModel) {
    super({
      x: tank.position.x + config.model.width / 2 - config.bullet.width / 2,
      y: tank.position.y + config.model.height / 2 - config.bullet.height / 2
    })

    this.direction = tank.direction as unknown as directionEnum
  }

  render(): void {
    let x = this.position.x
    let y = this.position.y
    let step = this.tank.name === 'player' ? 5 : 1.5
    switch (this.direction) {
      case directionEnum.top:
        y -= step
        break
      case directionEnum.right:
        x += step
        break
      case directionEnum.bottom:
        y += step
        break
      case directionEnum.left:
        x -= step
        break
    }
    // 敌方坦克列表
    const enemyList = ['enemy', 'big', 'quick', 'red']
    // 可被摧毁的模型列表
    const destroyList = ['wall', 'boss', 'enemy', 'big', 'quick', 'red', 'player']
    // 模型碰撞
    const modelTouch = touchUtil.isModelTouch(x, y,config.bullet.width ,config.bullet.height,
        [...wall.models, ...steels.models, ...boss.models, ...enemy.models, ...player.models
    ])
    //  子弹碰撞到物体 子弹不是该坦克的子弹(否则子弹原地爆炸  敌人不能打敌人(敌人的子弹可穿透敌人坦克)
    if (modelTouch  && modelTouch.name !== this.tank.name  && (!enemyList.includes(modelTouch.name) || this.tank.name === 'player')) {
      this.destroy()
      // 可被摧毁的模型
      if (destroyList.includes(modelTouch.name)) {
        modelTouch.destroy()
        // 为了播放声音 敌方坦克爆炸时可播放
        if (enemyList.includes(modelTouch.name)) {
          audio.blast().then()
        }
      }
      this.blast(modelTouch)
    }
    // 画布碰撞检测
    if (touchUtil.isCanvasTouch(x, y, 8, 8)) {
      this.destroy()
    } else {
      this.position.x = x
      this.position.y = y
    }
    this.draw()
  }

  // 绘制子弹
  protected draw() {
    this.canvas.ctx.drawImage(this.image(), this.position.x, this.position.y, config.bullet.width, config.bullet.height)
  }
}
